<template>
  <div style="background-color:#F5F5F5;">
    <div style="position: sticky;top: 0; z-index:2000">
      <el-menu :default-active="this.$router.path" router class="home-header-top el-menu-demo" mode="horizontal"
               @select="handleSelect" text-color="#111111" active-text-color="#111111" style="display: flex;">
        <div style="width: 17%"></div>
        <a @click="a_click()" href="/#/" style="margin: auto;font-size: 20px; text-decoration: none;">共享课程平台</a>
        <el-submenu index="/homeView" style="margin: auto;">
          <a slot="title" style="font-size: 16px;">课程</a>
          <div style="width: 600px;">
            <p style="margin:10px 0 0 50px;color: #999999;font-size: 12px;">
              共享课程平台，为你打造更舒适的在线学习环境</p>
            <div style="width: 600px;padding: 20px">
              <el-button v-for="(item,index) in fathertypeList"
                         style="width: 130px;margin: 5px;background-color: rgba(0, 0, 0, 0.04)"
                         @click="onFatherTypeBut(item.fathertypeId)" round>{{ item.fathertypeName }}
              </el-button>
            </div>
          </div>
        </el-submenu>
        <el-menu-item index="/schoolList" style="margin: auto;">合作组织</el-menu-item>
<!--        <el-menu-item index="3" style="margin: auto;">消息中心</el-menu-item>-->
        <el-menu-item index="/courseEditList" style="margin: auto;">授课管理</el-menu-item>
        <el-input v-model="input" placeholder="请输入内容" style="margin: auto;width: 300px">
          <el-button slot="append" @click="on_seach()" icon="el-icon-search"></el-button>
        </el-input>
        <a id="login-but" @click="showLoginDialog()" style="margin: auto;cursor:pointer;font-size: 14px">登录 | 注册</a>
        <div id="logout-but" style="display: none">
          <el-submenu index="" style="margin: auto;">
            <router-link slot="title" to="/userHome">
              <img :src="`http://localhost:8089/upload/${userData.avatar}`"
                                                          style="height: 40px;width: 40px;border-radius:50%;padding: 0 15px"/>
            </router-link>
            <el-menu-item index="/userHome">我的课程</el-menu-item>
            <el-menu-item index="/userSetting">设置</el-menu-item>
            <el-divider class="user-divder"/>
            <el-menu-item @click="on_logout()">退出</el-menu-item>
          </el-submenu>
        </div>
        <div style="width: 17%"></div>
      </el-menu>
    </div>
    <!--插入内容页-->
    <router-view style="min-height: 920px"/>
    <div style="background-color: #272727;height: 150px">
      <div style="display: flex;width: 100%">
        <div style="width: 15%"></div>
        <div style="margin: auto">
          <p style="font-size: 20px;color:#fff;">共享课程平台</p>
          <p style="font-size:12px;color:#999999;">
            由三明学院21计科孙乐麟开发，用于提高学生学习效率，共享学习资源，教学相长。</p>
        </div>
        <div style="margin: auto">
          <p style="color:#CCCCCC;">关于我们</p>
          <a style="font-size:12px;color:#999999;cursor: pointer;" @click="openUs()">联系我们</a>
        </div>
        <div style="margin: auto">
          <p style="color:#CCCCCC;">关注我们</p>
          <a style="color:#999999;">链接</a>
        </div>
        <div style="width: 15%"></div>
      </div>
    </div>
    <el-dialog
        :visible.sync="dialogVisible"
        :before-close="closeDialog"
        width="30%"
        top="300px"
        center>
      <div v-if="!registerDialog&&!findDialog">
        <el-tabs v-model="loginActiveName" @tab-click="handleLoginClick" stretch>
          <el-tab-pane label="邮箱登录" name="first" style="padding:0 75px;text-align: center;">
            <el-form :model="login" :rules="rules" v-if="!registerDialog" key="emailLoginForm" ref="emailLoginForm">
              <el-form-item :label-width="formLabelWidth" prop="email">
                <el-input v-model="login.email" autocomplete="off" placeholder="请输入邮箱"
                          style="width: 360px;height: 46px;margin-top: 30px">
                  <i slot="prefix" class="el-input__icon el-icon-message" style="font-size: 20px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="password">
                <el-input v-model="login.password" type="password" autocomplete="off" placeholder="请输入密码"
                          style="width: 360px;height: 46px;margin-top: 10px" show-password>
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="账号登录" name="second" style="padding:0 75px;text-align: center;">
            <el-form :model="login" :rules="rules" v-if="!registerDialog" key="userNameLoginForm"
                     ref="userNameLoginForm">
              <el-form-item :label-width="formLabelWidth" prop="userName">
                <el-input v-model="login.userName" autocomplete="off" placeholder="请输入用户名"
                          style="width: 360px;height: 46px;margin-top: 30px">
                  <i slot="prefix" class="el-input__icon el-icon-user" style="font-size: 20px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="password">
                <el-input v-model="login.password" type="password" autocomplete="off" placeholder="请输入密码"
                          style="width: 360px;height: 46px;margin-top: 10px" show-password>
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <a @click="showFind()" style="margin-left: 75px;color:#409EFF;cursor: pointer;">忘记密码</a>
        <a @click="showRegister()" style="margin-left: 255px;color:#409EFF;cursor: pointer;">去注册></a>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="loginUser()" style="width: 360px;height: 46px;">确 定</el-button>
    </span>
      <div v-if="registerDialog">
        <el-tabs v-model="loginActiveName" @tab-click="handleLoginClick" stretch>
          <el-tab-pane label="注册账号" name="register" style="padding:0 75px;text-align: center;">
            <el-form :model="register" :rules="registerRules" v-if="registerDialog" key="registerForm"
                     ref="registerForm">
              <el-form-item :label-width="formLabelWidth" prop="email">
                <el-input v-model="register.email" autocomplete="off" placeholder="请输入邮箱"
                          style="width: 360px;height: 46px;margin-top: 30px">
                  <i slot="prefix" class="el-input__icon el-icon-message" style="font-size: 20px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="userName">
                <el-input v-model="register.userName" autocomplete="off" placeholder="请输入用户名"
                          style="width: 360px;height: 46px;margin-top: 10px">
                  <i slot="prefix" class="el-input__icon el-icon-user" style="font-size: 20px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="password">
                <el-input v-model="register.password" type="password" autocomplete="off" placeholder="请输入密码"
                          style="width: 360px;height: 46px;margin-top: 10px" show-password>
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="passwordConfirm">
                <el-input v-model="register.passwordConfirm" type="password" autocomplete="off"
                          placeholder="请输入确认密码"
                          style="width: 360px;height: 46px;margin-top: 10px" show-password>
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="code">
                <el-input v-model="register.code" autocomplete="off" placeholder="请输入验证码"
                          style="width: 360px;height: 46px;margin-top: 10px">
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
                </el-input>
                <button @click.prevent="getCode()" class="code-btn" :disabled="!showCode">
                  <span v-show="showCode">获取验证码</span>
                  <span v-show="!showCode" class="count">{{ count }} s</span>
                </button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-if="findDialog">
        <el-tabs v-model="loginActiveName" @tab-click="handleLoginClick" stretch>
          <el-tab-pane label="重置密码" name="find" style="padding:0 75px;text-align: center;">
            <el-form :model="register" :rules="registerRules" v-if="findDialog" key="findForm" ref="findForm">
              <el-form-item :label-width="formLabelWidth" prop="email">
                <el-input v-model="register.email" autocomplete="off" placeholder="请输入邮箱"
                          style="width: 360px;height: 46px;margin-top: 30px">
                  <i slot="prefix" class="el-input__icon el-icon-message" style="font-size: 20px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="password">
                <el-input v-model="register.password" type="password" autocomplete="off" placeholder="请输入密码"
                          style="width: 360px;height: 46px;margin-top: 10px" show-password>
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
                </el-input>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" prop="code">
                <el-input v-model="register.code" autocomplete="off" placeholder="请输入验证码"
                          style="width: 360px;height: 46px;margin-top: 10px">
                  <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px;"></i>
                </el-input>
                <button @click.prevent="getCode()" class="code-btn" :disabled="!showCode">
                  <span v-show="showCode">获取验证码</span>
                  <span v-show="!showCode" class="count">{{ count }} s</span>
                </button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'App',
  provide() {
    return {
      showLoginDialog: this.showLoginDialog
    }
  },
  data() {
    return {
      login: {},
      register: {},
      loginActiveName: 'first',
      userData: {},
      fathertypeList: [],
      input: '',
      dialogVisible: false,
      registerDialog: false,
      showCode: true,
      count: '',
      formLabelWidth: "",
      findDialog: false,
      rules: {
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        userName: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ]
      },
      registerRules: {
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        userName: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {
            pattern: /^(?=.*[a-zA-Z])[a-zA-Z0-9]{6,18}$/,
            message: '密码应是6-18位字符至少包含1个英文字母',
            trigger: 'blur'
          }
        ],
        passwordConfirm: [
          {required: true, message: '再次输入您的密码', trigger: 'blur'},
          {
            pattern: /^(?=.*[a-zA-Z])[a-zA-Z0-9]{6,18}$/,
            message: '密码应是6-18位字符至少包含1个英文字母',
            trigger: 'blur'
          }
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {pattern: /^[0-9]{6}$/, message: '验证码应是6位数字', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    showLoginDialog() {
      this.login = {};
      this.register = {};
      this.loginActiveName = 'first';
      this.registerDialog = false;
      this.findDialog = false;
      this.dialogVisible = true;
    },
    closeDialog() {
      //重置表单，在这个模块上其他方法都没这个好
      this.dialogVisible = false;
      setTimeout(() => {
        this.registerDialog = true;
        this.findDialog = false;
      }, 300)
    },
    showRegister() {
      this.loginActiveName = 'register';
      this.registerDialog = true;
    },
    showFind() {
      this.loginActiveName = 'find';
      this.findDialog = true;
    },
    handleLoginClick(tab, event) {
      console.log(tab, event);
    },
    handleClick(tab, event) {
      if (tab.name === "0") {
        this.getCouseAll();
      } else {
        this.courseList = [];
        this.getCourseByFatherType(tab.name);
      }
      //console.log(tab, event);
    },
    onFatherTypeBut(fathertypeId) {
      this.$router.push({path: '/courseTypeView/' + fathertypeId})
      this.$router.go(0)
    },
    loginUser() {
      if (this.loginActiveName === 'first') {
        this.$refs['emailLoginForm'].validate((valid) => {
          if (valid) {
            this.loginByEmail();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else if (this.loginActiveName === 'second') {
        this.$refs['userNameLoginForm'].validate((valid) => {
          if (valid) {
            this.loginByUserName();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else if (this.loginActiveName === 'register') {
        this.$refs['registerForm'].validate((valid) => {
          if (valid) {
            this.registerUser();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else if (this.loginActiveName === 'find') {
        this.$refs['findForm'].validate((valid) => {
          if (valid) {
            this.findPasswordUser();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    },
    loginByEmail() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/user/loginByEmail',
        data: this.login
      }).then(res => {
        if (res.data.code === 200) {
          localStorage.setItem('token', res.data.data.token);
          localStorage.setItem('userId', res.data.data.userId);
          localStorage.setItem('userName', res.data.data.userName);
          localStorage.setItem('avatar', res.data.data.avatar);
          this.$router.go(0);
          this.dialogVisible = false;
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => console.log(err));
    },
    loginByUserName() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/user/loginByUserName',
        data: this.login
      }).then(res => {
        if (res.data.code === 200) {
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('userId', res.data.userId);
          localStorage.setItem('userName', res.data.userName);
          localStorage.setItem('avatar', res.data.avatar);
          this.$router.go(0);
          this.dialogVisible = false;
        } else {
          this.$message.error("用户名或密码错误")
        }
      }).catch(err => console.log(err));
    },
    registerUser() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/user/registerByEmail',
        data: this.register
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("注册用户成功,请完善个人信息")
          this.login=this.register
          setTimeout(() => {
            this.loginByEmail()
            this.$router.push('/userSetting')
          },1000)
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => console.log(err));
    },
    findPasswordUser() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/user/findPassword',
        data: this.register
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("重置密码成功")
          this.showLoginDialog()
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => console.log(err));
    },
    getFathertypeAll() {
      this.$axios({
        method: 'get',
        url: 'http://localhost:8089/fathertype/findAll'
      }).then(res => {
        this.fathertypeList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    // 获取邮箱验证码
    getCode() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/code/request',
        data: {"email": this.register.email}
      }).then(res => {
        localStorage.setItem('permissionCode', res.data.data.permissionCode);
      }).catch(err => console.log(err));
      setTimeout(() => this.getEmailCode(), 500)
    },
    getEmailCode() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/code/email',
        data: {"email": this.register.email, "code": localStorage.getItem('permissionCode')}
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success("发送验证码成功")
          if (!this.timer) {
            this.count = 60;
            this.showCode = false;
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= 60) {
                this.count--;
              } else {
                this.showCode = true;
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(err => console.log(err))
    },
    a_click() {
      this.activeIndex = '1';
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    on_logout() {
      localStorage.clear();
      console.log(this.$route.fullPath)
      if (this.$route.fullPath !== '/homeView') {
        this.$router.push('/homeView')
      }
      this.$router.go(0)
    },
    on_seach(){
      if(this.input!==null&&this.input!=='')
        window.open(this.$router.resolve({path: '/search',query:{input:this.input,sortModel:'0'}}).href, '_blank');
      else
        this.$message.warning("搜索内容不能为空")
    },
    openUs() {
      this.$alert('邮箱：1376757343@qq.com', '联系我们', {
        confirmButtonText: '关闭',
        center: true,
        callback:action => {}
      });
    }
  },
  created() {
    if (localStorage.getItem('token') != null) {
      this.userData['userId'] = localStorage.getItem('userId');
      this.userData['userName'] = localStorage.getItem('userName');
      this.userData['avatar'] = localStorage.getItem('avatar');
    }
    this.getFathertypeAll();
  },
  mounted() {
    if (window.localStorage.getItem('token') != null) {
      document.getElementById("login-but").style.display = "none";
      document.getElementById("logout-but").style.display = "";
    }
  }
}
</script>

<style>
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}

.code-btn {
  width: 100px;
  height: 20px;
  position: absolute;
  top: 20px;
  right: 10px;
  z-index: 222;
  color: #409EFF;
  font-size: 14px;
  border: none;
  border-left: 1px solid #bababa;
  padding-left: 10px;
  background-color: #fff;
  cursor: pointer;
}
</style>

<style scoped>
/deep/ .home-header-top > .el-menu-item {
  font-size: 16px;
  border-bottom: none !important;
}

/deep/ .home-header-top > .el-menu-item.is-active {
  border-bottom: none !important;
  border-bottom-color: #111111 !important;
}

.home-header-top /deep/ .el-menu-item:hover {
  outline: 0 !important;
  color: #1989FA !important;
}

.home-header-top /deep/ .el-menu-item:active {
  outline: 0 !important;
  color: #409EFF !important;
}

/*下划线样式*/
.el-divider--horizontal {
  margin: 3px 3%;
  padding: 0;
  width: 94%;
  background: 0 0;
  border-top: 2px solid #e8eaec;
}

/* 短信验证码css */
.pr {
  position: relative;
}
</style>